from datetime import date, timedelta


from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodCategoryVisit
from .serializers import GoodsSerializer
from users.models import User

# 获取用户总数
class UserTotalCountView(APIView):
    def get(self, request):
        # 查询用户的总数
        count = User.objects.count()
        return Response({
            "count": count,
        })

# 获取日增用户
class UserIncrementCountView(APIView):
    def get(self, request):
        # 查询日增用户
        today = date.today()
        count = User.objects.filter(date_joined__gte=today).count()
        # 返回响应
        return Response({"count": count})


# 获取日活跃用户
class UserActiveCountView(APIView):
    def get(self, request):
        # 查询日活跃用户
        today = date.today()
        print("******", today)
        active_user = User.objects.filter(last_login__gte=today).count()
        # 返回响应
        return Response({"count": active_user})


# 日下单用户统计
class UserDayOrderCountView(APIView):
    def get(self, request):
        # 查询日下单用户
        today = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=today).all()
        # 返回响应
        return Response({"count": count})


# 月新增用户
class UserMonthIncreamentCountView(APIView):
    def get(self, request):
        # 1,获取当天日期
        today = date.today()

        # 2,获取30天前的日期
        old_date = today - timedelta(days=29)

        # 3,循环查出每天的新增数,添加列表
        users_list = []
        for i in range(0, 30):
            # 3,1 获取当天时间
            current_date = old_date + timedelta(days=i)

            # 3,2 获取当天时间的下一天
            next_date = old_date + timedelta(days=i + 1)

            # 3,3 查询新增数
            count = User.objects.filter(date_joined__gte=current_date, date_joined__lt=next_date).count()

            # 3,4 添加数据
            users_list.append({
                "date": current_date,
                "count": count
            })

        # 4,返回响应
        return Response(users_list)


# 日分类商品访问量

class UserDAyView(GenericAPIView):
    # 提取序列化器
    serializer_class = GoodsSerializer

    def get(self, request):
        # 获取访问量
        today = date.today()
        good_view = GoodCategoryVisit.objects.filter(date__gte=today).all()

        # 序列化
        serializer = self.get_serializer(instance=good_view, many=True)

        # 返回响应
        return Response(serializer.data)
















